import { HYEventStore } from 'hy-event-store'
import { getSongDetail, getSongLyric } from '../service/api_player'
import { parseLyric } from '../utils/parse-lyric'

// const audioContext = wx.createInnerAudioContext()
const audioContext = wx.getBackgroundAudioManager()

const playerStore = new HYEventStore({
	state: {
		isStop: false,

		id: 0,
		currentSong: {},
		durationTime: 0,
		lyricInfos: [],

		currentTime: 0,
		currentLyricIndex: -1,
		currentLyricText: '',

		playModeIndex: 0,
		isPlaying: false,
		playSongList: {},
		playSongIndex: 0
	},

	actions: {
		playMusicWithSongIdAction(ctx, { id }) {
			if (ctx.id == id) {
				this.dispatch('changeMusicPlayStatusAction', true)
				return
			}
			ctx.id = id
			ctx.currentSong = {}
			ctx.durationTime = 0
			ctx.lyricInfos = []
			ctx.currentTime = 0
			ctx.currentLyricIndex = -1
			ctx.currentLyricText = ''

			// 请求数据
			getSongDetail(id).then(res => {
				ctx.currentSong = res.songs[0]
				audioContext.title = res.songs[0].name
				ctx.durationTime = res.songs[0].dt
			})
			getSongLyric(id).then(res => {
				const lyricString = res.lrc.lyric
				const lyrics = parseLyric(lyricString)
				ctx.lyricInfos = lyrics
			})

			// 音乐播放
			audioContext.stop()
			audioContext.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
			audioContext.title = id
			audioContext.autoplay = true
			ctx.isPlaying = true

			this.dispatch('setupAudioContextListenerAction')
		},

		// 音乐事件监听
		setupAudioContextListenerAction(ctx) {
			// 监听歌曲可以播放
			audioContext.onCanplay(() => {
				audioContext.play()
			})

			// 时间变化的监听
			audioContext.onTimeUpdate(() => {
				const currentTime = audioContext.currentTime * 1000
				ctx.currentTime = currentTime

				if (!ctx.lyricInfos.length) return
				for (let i = 0; i < ctx.lyricInfos.length; i++) {
					const lyricInfo = ctx.lyricInfos[i]
					if (currentTime < lyricInfo.time) {
						const currentIndex = i - 1
						if (ctx.currentLyricIndex !== currentIndex) {
							const currentLyricInfo = ctx.lyricInfos[currentIndex]
							ctx.currentLyricIndex = currentIndex
							ctx.currentLyricText = currentLyricInfo.text
						}
						break
					}
				}
			})

			// 音乐播放结束的监听
			audioContext.onEnded(() => {
				this.dispatch('changeNewMusicAction')
			})

			// 监听音乐的播暂停
			audioContext.onPlay(() => {
				ctx.isPlaying = true
			})
			audioContext.onPause(() => {
				ctx.isPlaying = false
			})
			audioContext.onStop(() => {
				ctx.isPlaying = false
				ctx.isStop = true
			})
		},

		// 控制音乐的播放
		changeMusicPlayStatusAction(ctx, isPlaying = true) {
			ctx.isPlaying = isPlaying
			if (ctx.isPlaying && ctx.isStop) {
				audioContext.src = `https://music.163.com/song/media/outer/url?id=${ctx.id}.mp3`
				audioContext.title = ctx.currentSong.name
				ctx.isStop = false
			}
			ctx.isPlaying ? audioContext.play() : audioContext.pause()
		},

		// 上一首 / 下一首
		changeNewMusicAction(ctx, isNext = true) {
			let index = ctx.playSongIndex

			switch (ctx.playModeIndex) {
				case 0:
					// 顺序播放
					index = isNext ? index + 1 : index - 1
					if (index == -1) index = ctx.playSongList.length - 1
					if (index == ctx.playSongList.length) index = 0
					break
				case 1:
					// 单曲循环
					break
				case 2:
					// 随机播放
					index = Math.floor(Math.random() * ctx.playSongList.length)
					break
			}

			let currentSong = ctx.playSongList[index]
			if (!currentSong) currentSong = ctx.currentSong
			else ctx.playSongIndex = index

			// 播放歌曲
			this.dispatch('changeMusicPlayStatusAction', { id: currentSong.id })
		}
	}
})

export { audioContext, playerStore }
